package com.example.redisLock.controller;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lxf
 * @description
 * @date 2021/3/8 22:45
 */
@RequestMapping("/buyController")
@RestController
public class BuyController {

    Logger log = LoggerFactory.getLogger(BuyController.class);
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${server.port}")
    private Integer serverPort;

    @Autowired
    private Redisson redisson;

    public static final String REDIS_LOCK = "demo";
    @RequestMapping("/buy")
    public String buy() {
        RLock lock = redisson.getLock(REDIS_LOCK);
        lock.lock();
        try {
            String stockStr = redisTemplate.opsForValue().get("good:001");
            int stock = stockStr == null ? 0 : Integer.parseInt(stockStr);
            if (stock > 0) {
                stock--;
                //设置到缓存redis
                redisTemplate.opsForValue().set("good:001", String.valueOf(stock));
                log.info("成功购买到商品,剩余库存数量：{}，服务端口：{}", stock, serverPort);
                return "成功购买到商品，剩余库存数量：" + stock + ",服务端口：" + serverPort;
            }
            log.info("商品已售罄，服务端口：{}", serverPort);
            return "商品已售罄，服务端口：" + serverPort;
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
